package com.leetcode.题库.score1;

import java.util.HashSet;
import java.util.Scanner;

/**
 * @BelongsProject: LeetCode
 * @BelongsPackage: com.leetcode.题库.score1
 * @Author: lei
 * @CreateTime: 2024-03-25  16:14
 * @Description: TODO
 * @Version: 1.0
 */
public class 核酸检测 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            int number = Integer.parseInt(sc.nextLine());
            String s1 = sc.nextLine();
            int[][] ints = new int[number][number];
            for (int i = 0; i < number; i++) {
                String s2 = sc.nextLine();
                String[] split = s2.split(",");
                for (int j = 0; j < split.length; j++) {
                    ints[i][j] = Integer.parseInt(split[j]);
                }
            }
            String[] split = s1.split(",");
            HashSet<Integer> hashSet = new HashSet<>();
            for (String s : split) {
                hashSet.add(Integer.parseInt(s));
            }
            int[] visInts = new int[number];
            for (String s : split) {
                int person = Integer.parseInt(s);
                dfs(visInts, ints, person);
            }
            int result = 0;
            for (int i = 0; i < visInts.length; i++) {
                if (visInts[i] == 1 & !hashSet.contains(i)) {
                    result++;
                }
            }
            System.out.println(result);
        }
    }

    private static void dfs(int[] visInts, int[][] ints, int person) {
        visInts[person] = 1;
        for (int i = 0; i < ints.length; i++) {
            if (ints[person][i] == 1 && visInts[person] == 0) {
                dfs(visInts, ints, i);
            }
        }
    }
}
